package com.dx.mes.service.warehouse.service;

import com.dx.common.table.ppt.Bis_data;
import com.dx.common.table.ppt.Ret_prd_info;
import com.dx.common.table.ppt.Ret_wo;
import com.dx.mes.common.bean.erp.EWOWHIN;
import com.dx.mes.common.core.rabbitmq.BaseConnFactory;
import com.dx.mes.common.dao.IBisDataDao;
import com.dx.mes.common.dao.IRetPrdInfoDao;
import com.dx.mes.common.dao.IRetWODao;
import com.dx.mes.common.transcoder.util.*;
import com.dx.mes.facade.warehouse.service.IMwphalfwhinService;
import com.dx.mes.facade.warehouse.tx.Mwphalfwhin.MwphalfwhinI;
import com.dx.mes.facade.warehouse.tx.Mwphalfwhin.MwphalfwhinIA;
import com.dx.mes.facade.warehouse.tx.Mwphalfwhin.MwphalfwhinO;
import com.dx.mes.facade.warehouse.tx.Mwphalfwhin.MwphalfwhinOA;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.dx.mes.common.bean.def.GenericDef.*;

/**
 * Created by admin on 2018/4/14.
 */
@Service("mwphalfwhinService")
public class MwphalfwhinService implements IMwphalfwhinService{
    private static final String TX_NAME = T_MWPHALFWHIN;
    private LogUtils logUtils;

    @Autowired
    private IRetPrdInfoDao retPrdInfoDao;
    @Autowired
    private IRetWODao retWODao;
    @Autowired
    private IBisDataDao bisDataDao;
    @Resource
    private BaseConnFactory baseConnFactory;

    @Override
    public String subMainProc(String evt_no, String strInTrx) {
        AppContext.clear();
        AppContext.setCurrServiceName(MwphalfwhinService.class.getSimpleName());
        AppContext.setCurrEventNumber(evt_no);
        logUtils = new LogUtils(MwphalfwhinService.class);
        logUtils.info("[InTrx:" + strInTrx + "]");
        String outMsg = null;
        Session session = retPrdInfoDao.getCrSession();
        MwphalfwhinO outTrx = new MwphalfwhinO();
        String strOutTrx = null;

        outTrx.setTrx_id(TX_NAME);
        outTrx.setType_id(TRX_OUT);
        outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));

        // 输入对象
        try {
            MwphalfwhinI inTrx = new MwphalfwhinI();
            // 将json字符串转换成对象
            inTrx = JacksonUtil.fromJson(strInTrx, MwphalfwhinI.class);
            char action_flg = inTrx.getAction_flg().charAt(0);

            switch (action_flg) {
                case 'Q':
                    queryByCondition(inTrx, outTrx);
                    break;
                case 'I':
                    halfWhInFnc(inTrx, outTrx);//入库
                    break;
                default:
                    errActionFnc(outTrx);
            }
            if (RETURN_CODE_OK.equals(outTrx.getRtn_code())) {
                session.flush();
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } catch (Exception ex) {
            outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
            outTrx.setRtn_mesg(ex.toString());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            outMsg = JacksonUtil.toJSONStr(outTrx);
            logUtils.info("[OutTrx:" + outMsg + "]");
        }
        strOutTrx = JacksonUtil.toJSONStr(outTrx);
        logUtils.info("[OutTrx:" + strOutTrx + "]");
        return strOutTrx;
    }
    public void queryByCondition(MwphalfwhinI inTrx, MwphalfwhinO outTrx) {

        String hql = "From Ret_prd_info where (prd_stat='WAIT'or prd_stat='HOMP')  ";
        if (!Util.isSpaceCheck(inTrx.getPrd_seq_id())) {
            hql = hql + "and prd_seq_id = '" + inTrx.getPrd_seq_id() + "'";
        }
        if (!Util.isSpaceCheck(inTrx.getWo_id_fk())) {
            hql = hql + " and wo_id_fk = '" + inTrx.getWo_id_fk() + "'";
        }
        List<Ret_prd_info> ret_prd_infoList = retPrdInfoDao.find(hql);
        List<MwphalfwhinOA> oaryList = new ArrayList<>();

        for(Ret_prd_info ret_prd_info : ret_prd_infoList){

            MwphalfwhinOA oary = new MwphalfwhinOA();
            oary.setPrd_seq_id(ret_prd_info.getPrd_seq_id());
            oary.setWo_id_fk(ret_prd_info.getWo_id_fk());
            oary.setMdl_id_fk(ret_prd_info.getMdl_id_fk());
            oary.setCr_ope_id_fk(ret_prd_info.getCr_ope_id_fk());
            oary.setPrd_stat(ret_prd_info.getPrd_stat());
            oary.setDest_shop(ret_prd_info.getDest_shop());

            //判断箱子当前入库状态
            if(PROC_WAIT.equals(ret_prd_info.getPrd_stat()) && Util.isSpaceCheck(ret_prd_info.getBnk_flg())){
                oary.setWhin_stat("等待申请");
            }
            if(PROC_SHIP.equals(ret_prd_info.getPrd_stat()) && BANK_IN.equals(ret_prd_info.getBnk_flg())){
                oary.setWhin_stat("已经申请");
            }
            if(PROC_SHIP.equals(ret_prd_info.getPrd_stat()) && BANK_COMP.equals(ret_prd_info.getBnk_flg())){
                oary.setWhin_stat("入库完成");
            }
            oaryList.add(oary);
        }
        outTrx.setOary(oaryList);
        outTrx.setRtn_code(RETURN_CODE_OK);
        outTrx.setRtn_mesg(RETURN_MESG_OK);
        return;
    }
    public void halfWhInFnc(MwphalfwhinI inTrx, MwphalfwhinO outTrx) {

        String  mtrlProcId = inTrx.getMtrl_proc_id();
        String  destShop   = inTrx.getDest_shop();
        String  evtUsr =inTrx.getEvt_usr();
        String  mesRsvNo = "H"+ GUIDGenerator.javaGUID().substring(0,11);
        Timestamp gEvtTimestamp = Util.getCurrentTimestamp();

        List<MwphalfwhinIA> iaryList = inTrx.getIary();
        List<Ret_prd_info>  prdInfoList = new ArrayList<>();
        if(iaryList!=null && iaryList.size()>0){
            for(MwphalfwhinIA iary :iaryList){

                Ret_prd_info ret_prd_info = retPrdInfoDao.get(iary.getPrd_seq_id());
                if(!"REWFMA01".equals(ret_prd_info.getNx_path_id_fk())){
                    outTrx.setRtn_code(E_BIS_PATHI + E_READ_NOT_FOUND + "");
                    outTrx.setRtn_mesg("屏体当前不在FMA站点，不能入库");
                    return;
                }
                ret_prd_info.setDest_shop(inTrx.getDest_shop());
                ret_prd_info.setPrd_stat(PROC_HOMP );
                ret_prd_info.setRsv_no(mesRsvNo);
                ret_prd_info.setBnk_flg(BANK_IN);
                ret_prd_info.setEvt_cate(EVT_HALF_WHIN);
                ret_prd_info.setEvt_usr(evtUsr);
                ret_prd_info.setEvt_timestamp(gEvtTimestamp);
                ret_prd_info.setWh_in_timestamp(gEvtTimestamp);
                prdInfoList.add(ret_prd_info);
            }
            retPrdInfoDao.saveOrUpdateAll(prdInfoList);

            //入库后信息发给SAP
            List<EWOWHIN> ewowhinList = new ArrayList<EWOWHIN>();
            Ret_wo   ret_wo = retWODao.get(prdInfoList.get(0).getWo_id_fk());
            if(ret_wo!=null){
                EWOWHIN ewowhin = new EWOWHIN();
                ewowhin.setAUFNR(ret_wo.getWo_id());
                ewowhin.setAUART(ret_wo.getWo_cate());
                ewowhin.setWEMPF(mesRsvNo);
                ewowhin.setMATNR(mtrlProcId);//半成品料号
                ewowhin.setMENGE(prdInfoList.size());
                ewowhin.setMEINS("PCS");
                ewowhin.setCHARG("H"+ret_wo.getWo_id());//批次号
                ewowhin.setZBWART("Z05");
                ewowhin.setBWART("531");
                ewowhin.setWERKS(ret_wo.getFab_id_fk());//工厂
                String hqlA ="FROM Bis_data where data_cate ='DEST' and data_ext ='" + destShop + "'";
                List<Bis_data> destList = bisDataDao.find(hqlA);
                if(destList!=null && destList.size()>0){
                    ewowhin.setLGORT(destList.get(0).getExt_2());//接受仓位
                }
                ewowhin.setUMLGO(destShop);//发出库存地址
                Format dateFormat = new SimpleDateFormat("yyyyMMdd");
                String date  = dateFormat.format(new Date());
                ewowhin.setHSDAT(date);
                ewowhin.setBUDAT(date);
                ewowhinList.add(ewowhin);
//                try {
//                    baseConnFactory.addSAPREQProc("EWOWHIN", JacksonUtil.toJSONStr(ewowhinList));
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
            }
        }
        outTrx.setRtn_code(RETURN_CODE_OK);
        outTrx.setRtn_mesg(RETURN_MESG_OK);
        return;
    }
    public void errActionFnc( MwphalfwhinO outTrx) {
        outTrx.setRtn_code("0000009");
        outTrx.setRtn_mesg("Invalid Action_flg");
    }

}
